package com.cd.song.controller;

import com.cd.common.controller.BaseController;
import com.cd.common.domain.AjaxResult;
import com.cd.common.util.TableDataInfo;
import com.cd.song.api.SongService;
import com.cd.song.jpa.domain.Song;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/songs")
public class SongController extends BaseController {

    @Autowired
    private SongService songService;

    /**
     * @Description
     * @Author lqq
     * @Date 2025/5/24 13:47
     **/
    @GetMapping
    public TableDataInfo getAllSongs(Song song) {
        startPage();
        return getDataTable(songService.findAll(song));
    }

    @GetMapping("/{id}")
    public AjaxResult getSongById(@PathVariable(value = "id") Long songId) {
        Optional<Song> song = songService.findById(songId);
        if (song.isPresent()) {
            return success(song.get());
        } else {
            return error("未找到对应id的歌曲");
        }
    }

    @PostMapping
    public AjaxResult createSong(@RequestBody Song song) {
        return success(songService.save(song));
    }

    @PutMapping("/{id}")
    public AjaxResult updateSong(@PathVariable(value = "id") Long songId, @RequestBody Song songDetails) {
        Optional<Song> optionalSong = songService.findById(songId);
        if (optionalSong.isPresent()) {
            Song song = optionalSong.get();
            song.setTitle(songDetails.getTitle());
            song.setType(songDetails.getType());
            song.setArtist(songDetails.getArtist());
            song.setUserId(songDetails.getUserId());
            final Song updatedSong = songService.save(song);
            return success(updatedSong);
        } else {
            return error("歌曲不存在");
        }
    }

    @DeleteMapping("/{id}")
    public AjaxResult deleteSong(@PathVariable(value = "id") Long songId) {
        Optional<Song> song = songService.findById(songId);
        if (song.isPresent()) {
            songService.deleteById(songId);
            return success("ok");
        } else {
            return error("error");
        }
    }
}